<template>
  <div
    class="update-box"
    :class="{ isTriggerHide: isTriggerHide, isDisabled: isDisabled }"
  >
    <el-upload
      class="upload"
      ref="uploadImportEdit"
      name="file"
      :file-list="fileList"
      :action="'#'"
      :show-file-list="showFileList"
      :accept="format"
      :multiple="isMultiple"
      :limit="limit"
      :list-type="listType"
      :disabled="isDisabled"
      :before-upload="beforeUpload"
      :http-request="handleHttpRequest"
      :on-exceed="handleExceed"
    >
      <template v-slot:file="{ file }">
        <slot>
          <img
            :src="file.url"
            class="upload-image"
          />
          <div
            class="upload-handle"
            @click.stop
          >

            <div
              class="handle-icon del"
              @click="deleteFile(file)"
            >
              <el-icon>
                <Delete />
              </el-icon>
              <span>删除</span>
            </div>
          </div>
        </slot>
      </template>
      <template v-slot:trigger>
        <slot name="empty">
          <div class="upload-empty">
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </div>
        </slot>
      </template>
    </el-upload>

  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { singleUpload } from "@/api/upload/index.js";
import { computed, } from 'vue';
defineOptions({
  name: "AssmentUpload",
})
const props = defineProps({
  fileList: {
    type: Array,
    // required: true,
    default: () => [
      // {
      //   name: "默认",
      //   url: "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg",
      //   id: "123",
      // },
    ],
  },
  format: {
    //默认上传格式
    type: String,
    default: () => ".jpg,.png,.jpeg,.webp",
  },
  fileSize: {
    // 文件大小
    type: [String, Number],
    default: 5,
  },

  // 上传格式
  listType: {
    // default: () => "picture",
    // default: () => "text",
    default: () => "picture-card",
  },

  // 是否支持多选
  isMultiple: {
    type: Boolean,
    default: true,
  },

  // 最大上传多少个
  limit: {
    type: Number,
    default: 2,
  },

  isDisabled: {
    type: Boolean,
    default: false,
  },

  // 是否显示文件列表
  showFileList: {
    type: Boolean,
    default: true,
  },

  // 当上传文件达到最大限制时是否隐藏上传框
  isFileMaxLimitHide: {
    type: Boolean,
    default: true,
  },
})
const emits = defineEmits(["update:fileList", "handleSuccess", "handleError"]);

const isTriggerHide = computed(() => {
  return props.isFileMaxLimitHide && props.fileList.length >= props.limit;
})
/**
    * 上传之前
    */
function beforeUpload (file) {
  if (file.size / 1024 / 1024 > props.fileSize) {
    ElMessage.warning(`文件大小不能超过${props.fileSize}MB!`);
    emits("update:fileList", props.fileList);
    return Promise.reject();
  }
  return Promise.resolve();
}

function handleExceed (files, fileList) {
  // ElMessage.warning(
  //   `当前限制选择 ${this.limit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
  //     files.length + fileList.length
  //   } 个文件`
  // );
  ElMessage.warning(`最多只能上传 ${props.limit} 个文件`);
}

/**
 * 上传
 */
async function handleHttpRequest (options) {
  try {
    let formData = new FormData();
    formData.append("file", options.file);
    formData.append("fileName", options.file.name);
    const result = await singleUpload(formData);
    if (result.code == 200) {
      handleSuccess(result);
    }
    // return Promise.resolve(result);
  } catch (error) {
    // return Promise.reject(error);
    handleError();
  }
}

/**
 * 成功
 */
function handleSuccess (response) {
  let { url } = response;
  let fileName = /([^\/]+)\.\w+$/.exec(url)[1];
  // let uid = fileName + Date.now();
  let obj = {
    name: fileName,
    url,
    // uid,
  };
  emits("update:fileList", [...props.fileList, obj]);

  emits("handleSuccess", obj);
}

/**
 * 失败
 */
function handleError () {
  emits("update:fileList", props.fileList);
  emits("handleError");

  ElMessage.error("文件上传失败");
}

/**
 * @description 删除图片
 * */
function deleteFile (file) {
  if (props.isDisabled) return;
  emits(
    "update:fileList",
    // props.fileList.filter((item) => item.uid !== file.uid)
  );
}
</script>

<style lang="scss" scoped>
::v-deep(.update-box) {
  $width: 100%;
  $height: 100%;
  .el-upload-list,
  .upload {
    width: $width;
    display: flex;
    flex-wrap: wrap;
    // row-gap: 8px;
    // column-gap: 8px;
  }

  // 每一项图片
  .el-upload-list__item {
    flex: 1;
    // width: $width;
    position: relative;
    padding: 1px;
    // margin: 0px;
    img {
      width: $width;
      height: $height;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 6px;
    }
    &:hover {
      // border-color: var(--el-color-primary);
      .upload-handle {
        opacity: 1;
        background-color: rgba($color: #000000, $alpha: 0.5);
      }
    }
    .upload-handle {
      box-sizing: border-box;
      position: absolute;
      top: 0;
      right: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      opacity: 0;
      width: 100%;
      height: 100%;
      transition: var(--el-transition-duration-fast);
      .handle-icon {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 0 6%;
        color: aliceblue;
        cursor: pointer;
        .el-icon {
          margin-bottom: 40%;
          font-size: 130%;
          line-height: 130%;
        }
        span {
          font-size: 85%;
          line-height: 85%;
        }
      }
    }
  }

  &.isDisabled {
    .handle-icon.del {
      cursor: not-allowed;
    }
    .el-upload {
      background: #f5f6fc;
      cursor: not-allowed;
      &:hover {
        border-color: #d5d5d5;
      }
    }
  }

  &.isTriggerHide {
    .el-upload {
      display: none;
    }
  }
  .el-upload {
    width: $width;
    height: $height;
    line-height: $height;
  }
}
</style>
